package edu.zut.main.thread;

public class ThreadTicket {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        SaleTicketThread saleTicketThread = new SaleTicketThread(ticket);
        SaleTicketThread saleTicketThread2 = new SaleTicketThread(ticket);
        SaleTicketThread saleTicketThread3 = new SaleTicketThread(ticket);
        new Thread(saleTicketThread,"小花").start();
        new Thread(saleTicketThread2,"小李").start();
        new Thread(saleTicketThread3,"小郭").start();

    }
}
class SaleTicketThread implements Runnable{
    private Ticket ticket;

    public SaleTicketThread(Ticket ticket) {
        this.ticket = ticket;
    }

    @Override
    public void run(){
        //售票操作
        while(true) {
            synchronized (ticket) {
                if (ticket.getTicketNum() <= 0) {
                    break;
                }
                ticket.saleTickets();
            }
        }

    }
}
class Ticket{//余票


    private int ticketNum = 10;

    public int getTicketNum() {
        return ticketNum;
    }

    public synchronized void saleTickets(){
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"售出了第"+ticketNum-- +"张票");
    }
}
